package com.igeek.d0612;

import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhiyu
 * @Date:16:28
 * @DESC:
 */
public class Test1 {
    private static final ReentrantLock lock = new ReentrantLock(true); // 创建公平锁
    private static final Condition condition = lock.newCondition();
    private static volatile int count = 1;
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Printer(1),"线程1");
        Thread thread2 = new Thread(new Printer(0),"线程2");

        thread1.start();
        thread2.start();
    }

    static class Printer implements Runnable {
        private int threadId;

        public Printer(int id) {
            this.threadId = id;
        }

        @Override
        public void run() {
            while (count <= 10) {
                lock.lock();
                try {
                    if (count>10){
                        break;
                    }
                    if (count % 2 == threadId) {
                        System.out.println(Thread.currentThread().getName() + ": " + count);
                        count++;
                        condition.signal();
                    } else {
                        condition.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
